package store.aixx.jwt.demo.controller;

import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import store.aixx.jwt.demo.constant.AuthConstant;
import store.aixx.jwt.demo.domain.vo.Auth;
import store.aixx.jwt.demo.util.JwtUtil;

import java.nio.file.AccessDeniedException;

/**
 * @author yukai
 * @since 2021年12月11日 23:11
 */
@RequiredArgsConstructor
@RequestMapping("/authentication")
@RestController
public class AuthController {

    private final JwtUtil jwtUtil;

    @PostMapping("/token/refresh")
    public Auth refreshToken(
            @RequestHeader(AuthConstant.TOKEN_HEADER_NAME) String authorization,
            @RequestBody String refreshToken
    ) throws AccessDeniedException {
        // 验证accessToken
        String accessToken = authorization.replace(AuthConstant.TOKEN_PREFIX, "");
        if (jwtUtil.validateAccessTokenWithoutExpireation(accessToken) && jwtUtil.validateRefreshToken(refreshToken)){
            return new Auth(jwtUtil.createAccessTokenByRefreshToken(refreshToken), refreshToken);
        }
        throw new AccessDeniedException("访问被拒绝");
    }

    @GetMapping("/principal")
    public Authentication getPrincipal(){
        return SecurityContextHolder.getContext().getAuthentication();
    }

}
